package com.mzj.saas.mservice.smartlock.service.luoke;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.haixiaoke.saas.repository.pojo.SmartLock;
import com.haixiaoke.saas.repository.service.ISmartLockService;
import com.mzj.saas.commons.ResultBean;
import com.mzj.saas.commons.StatusCode;
import com.mzj.saas.mservice.lock.entity.LockAlarm;
import com.mzj.saas.mservice.lock.entity.LockOpenLog;
import com.mzj.saas.mservice.lock.entity.SmartLockAuth;
import com.mzj.saas.mservice.lock.service.LockAlarmService;
import com.mzj.saas.mservice.lock.service.LockOpenLogService;
import com.mzj.saas.mservice.smartlock.vo.luoke.LuoKeCallBackData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author panda
 * @Date 2024/1/25
 **/
@Slf4j
@Service
public class SmartLockLkEventHandleService {

    private static final String pwdSql = "SELECT a.id,a.user_name as userName  FROM saas_smart_lock_auth a "
            + "LEFT  JOIN  saas_smart_lock_pwd p ON a.id = p.lock_auth_id "
            + "WHERE p.identification = ?";

    private static final String cardSql = "SELECT a.id,a.user_name AS userName FROM saas_smart_lock_auth a LEFT JOIN "
            + "saas_smart_lock_card c ON a.id = c.lock_auth_id WHERE c.identification  = ?";

    private static final String faceSql = "SELECT a.id,a.user_name AS userName FROM saas_smart_lock_auth a LEFT JOIN "
            + "saas_smart_lock_face f ON a.id = f.lock_auth_id WHERE  f.identification = ?";

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private LockOpenLogService lockOpenLogService;
    @Autowired
    private ISmartLockService iSmartLockService;
    @Autowired
    private LockAlarmService lockAlarmService;
    @Autowired
    private SmartLockLkService smartLockLkService;

    /**
     * 开锁日志回调
     *
     * @param message
     * @return
     */
    public Map<String, Object> lockOpenLog(LuoKeCallBackData message) {
        Map<String, Object> resultMap = new HashMap<>();
        if (StrUtil.isBlank(message.getDeviceId()) || message.getMethod() == null) {
            resultMap.put("code", 500);
            resultMap.put("message", "参数不全");
        }
        try {
            SmartLock smartLock = iSmartLockService.selectBySn(message.getDeviceId());
            if (ObjectUtil.isNotEmpty(smartLock)) {
                // 开门记录
                LockOpenLog openLog = new LockOpenLog();
                switch (message.getMethod()) {
                    case 2:   //密码
                        openLog.setOpenMode(0);
                        List<SmartLockAuth> pwdAuth = jdbcTemplate.query(pwdSql, new BeanPropertyRowMapper<>(SmartLockAuth.class), message.getLockKeyId());
                        if (CollectionUtil.isNotEmpty(pwdAuth)) {
                            openLog.setUserId(pwdAuth.get(0).getId());
                            openLog.setOpenUserName(pwdAuth.get(0).getUserName());//开门人姓名
                        }
                        break;
                    case 3:     //卡片
                        openLog.setOpenMode(11);
                        List<SmartLockAuth> cardAuth = jdbcTemplate.query(cardSql, new BeanPropertyRowMapper<>(SmartLockAuth.class), message.getLockKeyId());
                        if (CollectionUtil.isNotEmpty(cardAuth)) {
                            openLog.setUserId(cardAuth.get(0).getId());
                            openLog.setOpenUserName(cardAuth.get(0).getUserName());//开门人姓名
                        }
                        break;
                    case 4:     //机械钥匙
                        openLog.setOpenMode(30);
                        break;
                    case 90:    //人脸
                        openLog.setOpenMode(32);
                        List<SmartLockAuth> faceAuth = jdbcTemplate.query(faceSql, new BeanPropertyRowMapper<>(SmartLockAuth.class), message.getLockKeyId());
                        if (CollectionUtil.isNotEmpty(faceAuth)) {
                            openLog.setUserId(faceAuth.get(0).getId());
                            openLog.setOpenUserName(faceAuth.get(0).getUserName());//开门人姓名
                        }
                        break;
                }
                if (openLog.getOpenMode() != null) {
                    openLog.setLockId(smartLock.getId());
                    openLog.setHouseId(smartLock.getHouseId());
                    openLog.setOpenType(1);// 开门类型：0未知 1外开门 2内开门
                    openLog.setBuildName(smartLock.getBuildName());
                    openLog.setCommunityName(smartLock.getCommunityName());
                    openLog.setUnitName(smartLock.getUnitName());
                    openLog.setMatchUserName(smartLock.getMatchUserName());
                    openLog.setRoomNumber(smartLock.getRoomNumber());
                    openLog.setOpenTime(message.getOperateTime());
                    openLog.setUserProperty(0);// 开门人性质：0未知 1承租人 2同住人
                    lockOpenLogService.save(openLog);
                }
            }
            resultMap.put("code", 200);
            resultMap.put("message", "success");
        } catch (Exception e) {
            log.error("络克锁回调数据--开门回调数据异常：{}", e.getMessage(), e);
            resultMap.put("code", 500);
            resultMap.put("message", "系统异常");
        }
        return resultMap;
    }

    /**
     * 锁状态回调
     *
     * @param message
     * @return
     */
    public Map<String, Object> lockStateLog(LuoKeCallBackData message) {
        Map<String, Object> resultMap = new HashMap<>();
        if (StrUtil.isBlank(message.getDeviceId()) || StrUtil.isBlank(message.getOnlineState())) {
            resultMap.put("code", 500);
            resultMap.put("message", "参数不全");
        }
        try {
            SmartLock smartLock = iSmartLockService.selectBySn(message.getDeviceId());
            if (ObjectUtil.isNotEmpty(smartLock)) {
                switch (message.getOnlineState()) {
                    case "online":      //在线
                        smartLock.setOnlineStatus(1);
                        break;
                    case "offline":     //离线
                        smartLock.setOnlineStatus(0);
                        break;
                }
                ResultBean<String> lockDetail = smartLockLkService.getLockDetail(message.getDeviceId());
                if (StatusCode.SUCCESS_CODE_10000.getErrorCode().equals(lockDetail.getCode())) {
                    JSONObject lockDetailJson = JSONObject.parseObject(lockDetail.getResultData());
                    smartLock.setElectricQuantity(lockDetailJson.getInteger("electricity"));
                }
                iSmartLockService.updateById(smartLock);
            }
            resultMap.put("code", 200);
            resultMap.put("message", "success");
        } catch (Exception e) {
            log.error("络克锁回调数据--锁状态回调异常：{}", e.getMessage(), e);
            resultMap.put("code", 500);
            resultMap.put("message", "系统异常");
        }
        return resultMap;
    }

    /**
     * 锁告警回调
     *
     * @param message
     * @return
     */
    public Map<String, Object> lockWarnLog(LuoKeCallBackData message) {
        Map<String, Object> resultMap = new HashMap<>();
        if (StrUtil.isBlank(message.getDeviceId()) || message.getType() == null) {
            resultMap.put("code", 500);
            resultMap.put("message", "参数不全");
        }
        try {
            SmartLock smartLock = iSmartLockService.selectBySn(message.getDeviceId());
            if (ObjectUtil.isNotEmpty(smartLock)) {
                LockAlarm lockAlarm = new LockAlarm();
                switch (message.getType()) {
                    case 1:     //低压警报
                        lockAlarm.setAlarmType(1);
                        break;
                    case 3:     //防撬警报
                        lockAlarm.setAlarmType(2);
                        break;
                }
                if (lockAlarm.getAlarmType() != null) {
                    lockAlarm.setLockId(smartLock.getId());
                    lockAlarm.setHouseId(smartLock.getHouseId());
                    lockAlarm.setSn(smartLock.getSn());
                    lockAlarm.setAlarmTime(message.getAlarmTime());
                    ResultBean<String> lockDetail = smartLockLkService.getLockDetail(message.getDeviceId());
                    if (StatusCode.SUCCESS_CODE_10000.getErrorCode().equals(lockDetail.getCode())) {
                        JSONObject lockDetailJson = JSONObject.parseObject(lockDetail.getResultData());
                        smartLock.setElectricQuantity(lockDetailJson.getInteger("electricity"));
                        lockAlarm.setElectric(lockDetailJson.getInteger("electricity"));
                    }
                    lockAlarmService.save(lockAlarm);
                    iSmartLockService.updateById(smartLock);
                }
            }
            resultMap.put("code", 200);
            resultMap.put("message", "success");
        } catch (Exception e) {
            log.error("络克锁回调数据--锁告警回调异常：{}", e.getMessage(), e);
            resultMap.put("code", 500);
            resultMap.put("message", "系统异常");
        }
        return resultMap;
    }
}
